package raccoon.plugin.mybatis;

import org.apache.ibatis.executor.BatchExecutor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.defaults.DefaultSqlSession;
import org.apache.ibatis.transaction.Transaction;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/6/30.
 */
public class MyBatchExecutor extends BatchExecutor{


    protected MyBatchExecutor(Configuration configuration, Transaction transaction) {
        super(configuration, transaction);
    }

    public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {

        BoundSql boundSql = null;
        List<Object> batchList = null;

        if(parameterObject instanceof DefaultSqlSession.StrictMap){
            batchList = (List<Object>) ((Map<String,Object>)parameterObject).get("list");
            if(batchList==null ||batchList.isEmpty()) return 0;
            for(Object o : batchList){
                boundSql = ms.getBoundSql(o);
                break;
            }
        }
        else{
            boundSql = ms.getBoundSql(parameterObject);
            batchList = new ArrayList<>();
            batchList.add(parameterObject);
        }
        PreparedStatement stmt = null;
        try {
            StatementHandler handler = new BatchPreparedStatementHandler(this, ms,batchList,RowBounds.DEFAULT,null,boundSql);
            stmt = (PreparedStatement) handler.prepare(getConnection( ms.getStatementLog()), transaction.getTimeout());
            handler.parameterize(stmt);
            stmt.executeBatch();
        } finally {
            closeStatement(stmt);
        }
        return 1;
    }


}
